import { defineStore } from 'pinia';

import { getAccessCodesApi, getDictionary } from '#/api';

interface DictStore {
  [key: string]: any[];
}

export interface ButtonStore {
  /**
   * 按钮名称
   */
  name: string;

  /**
   * 按钮图标
   */
  source?: string;

  /**
   * 按钮功能
   */
  action: number;

  /**
   * 按钮权限码
   */
  code: string;

  /**
   * 所属模块code
   */
  moduleCode: string;

  /**
   * 按钮动作函数
   */
  actionFn: string;

  /** 按钮样式 */
  actionStyle?: string;
}

interface CommonState {
  /**
   * 字典集合
   */
  dicts: DictStore;

  /** 业务字典集合 */
  busDicts: DictStore;

  /**
   * 按钮缓存
   */
  buttons: Record<string, Record<string, ButtonStore[]>>;
}

export const useCommonStore = defineStore('common-store', {
  actions: {
    async fetchDicts(code: string) {
      try {
        const dicts = this.dicts || {};
        const data = await getDictionary({ code });
        dicts[code] = data;
        this.dicts = dicts;
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },
    async getDicts(code: string) {
      const dicts = this.dicts || {};
      if (!dicts[code]) {
        const data = await getDictionary({ code });
        dicts[code] = data;
        this.dicts = dicts;
      }
      return new Promise((resolve) => {
        try {
          resolve(this.dicts[code]);
        } catch (error) {
          console.error('获取数据失败:', error);
        }
      });
    },

    async getButtons() {
      const data = await getAccessCodesApi();
      const result: ButtonStore[] = [];
      const btnMap: any = {};
      const getCode = (list: any[]) => {
        list.forEach((ele) => {
          btnMap[ele.id] = ele.code;
          if (typeof ele === 'object') {
            const chiildren = ele.children;
            if (chiildren) {
              getCode(chiildren);
            } else {
              result.push({
                name: ele.name,
                source: ele.source,
                action: ele.action,
                code: ele.code,
                moduleCode: btnMap[ele.parentId],
                actionFn: '',
                actionStyle: ele.actionStyle,
              });
            }
          }
        });
      };
      getCode(data);
      const buttonData: Record<string, Record<string, ButtonStore[]>> = {};
      for (const item of result) {
        const moduleCodeMap = buttonData[item.moduleCode] || {
          [item.action]: [] as ButtonStore[],
        };
        const actions = moduleCodeMap[item.action] || [];
        // 将当前项添加到对应的数组中
        actions.push(item);
        moduleCodeMap[item.action] = actions;
        buttonData[item.moduleCode] = moduleCodeMap;
      }
      return new Promise((resolve) => {
        try {
          this.buttons = buttonData;
          resolve(buttonData);
        } catch (error) {
          console.error('获取数据失败:', error);
        }
      });
    },
  },
  persist: {
    // 持久化
    pick: ['dicts', 'buttons'],
    storage: sessionStorage,
  },
  state: (): CommonState => ({
    dicts: {},
    buttons: {},
    busDicts: {},
  }),
});
